package com.ruoyi.common.utils;

import java.util.Random;

public class ShareCodeUtil {
    private static final char[] r = new char[]{
        'q', 'w', 'e', '8', 'a', 's', '2', 'd', 'z', 'x',
        '9', 'c', '7', 'p', '5', 'i', 'k', '3', 'm', 'j',
        'u', 'f', 'r', '4', 'v', 'y', 'l', 't', 'n', '6',
        'b', 'g', 'h'};
    private static final int binLen = r.length;

    public static String getSerialCode(Integer id) {
        char[] buf = new char[32];
        int charPos = 32;
        while (id.intValue() / binLen > 0) {
            int ind = id.intValue() % binLen;
            buf[--charPos] = r[ind];
            id = Integer.valueOf(id.intValue() / binLen);
        }
        buf[--charPos] = r[id.intValue() % binLen];
        String str = new String(buf, charPos, 32 - charPos);
        if (str.length() < 8) {
            StringBuilder sb = new StringBuilder();
//            sb.append('o');
            sb.append('A');
            Random rnd = new Random();
            for (int i = 1; i < 8 - str.length(); i++) {
                sb.append(r[rnd.nextInt(binLen)]);
                str = str + sb;
            }
        }
        return str.toUpperCase();
    }

    public static Integer codeToId(String code) {
        char[] chs = code.toCharArray();
        Integer res = Integer.valueOf(0);
        for (int i = 0; i < chs.length; i++) {
            int ind = 0;
            for (int j = 0; j < binLen; j++) {
                if (chs[i] == r[j]) {
                    ind = j;
                    break;
                }
            }
            if (chs[i] == 'o') {
                break;
            }
            if (i > 0) {
                res = Integer.valueOf(res.intValue() * binLen + ind);
            } else {
                res = Integer.valueOf(ind);
            }
        }
        return res;
    }
}
